package com.zcmob.web.admanagement.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zcmob.web.admanagement.db.AppDao;
import com.zcmob.web.admanagement.util.StringUtils;
import com.zcmob.web.admanagement.vo.AdUser;
import com.zcmob.web.admanagement.vo.AppInfo;

/**
 * Servlet implementation class for Servlet: LoginServlet
 * 
 */
public class LoginServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
    static final long serialVersionUID = 1L;

    /*
     * (non-Java-doc)
     * 
     * @see javax.servlet.http.HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
    }

    /*
     * (non-Java-doc)
     * 
     * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request,
     *      HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
    }

    /*
     * (non-Java-doc)
     * 
     * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request,
     *      HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("UTF-8");
        request.setCharacterEncoding("UTF-8");

        String username = request.getParameter("username");
        String password = request.getParameter("pwd");
        
        if (StringUtils.isNullOrEmpty(username) || StringUtils.isNullOrEmpty(password)) {
            // goto error page
            return;
        }
        AdUser aduser = AppDao.getInstance().getAdUserByUsername(username);
        if (aduser == null) {
            // 
            request.setAttribute("validerror", "用户名不存在");
            RequestDispatcher rd = request.getRequestDispatcher("ad_login.jsp");
            rd.forward(request, response);
            return;
        } else if (!aduser.getPassword().equals(password)) {
            request.setAttribute("validerror", "用户名密码不匹配");
            RequestDispatcher rd = request.getRequestDispatcher("ad_login.jsp");
            rd.forward(request, response);
            return;
        }
        
        request.getSession().setAttribute("aduser", aduser);
        
        RequestDispatcher rd = request.getRequestDispatcher("s_applist");
        rd.forward(request, response);
    }
}